package com.supper.invincible_api.network.http;

import java.util.HashMap;
import java.util.Map;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.android.volley.*;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.supper.invincible_api.base.BaseApplication;
import com.supper.invincible_api.constant.Constants;
import com.supper.invincible_api.constant.HttpState;
import com.supper.invincible_api.network.http.entity.RequestData;
import com.supper.invincible_api.network.http.entity.ResponseData;

public class HttpRequest implements Response.Listener<String>,
		Response.ErrorListener {

	private IHttpRequest iHttpRequest = null;
	protected int requestCode = -1;

	public HttpRequest(IHttpRequest httpRequest) {
		this.iHttpRequest = httpRequest;
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		iHttpRequest.onVolleyError(error);
	}

	@Override
	public void onResponse(String response) {
		if (!TextUtils.isEmpty(response)) {
			// Logger.log("responseData:" + response.replace("\\", ""));
			ResponseData responseData = JSON.parseObject(response,
					ResponseData.class);
			if (responseData.getCode() == HttpState.HTTP_OK) {
				if (responseData.getExtra() != null) {
					iHttpRequest.accessSucc(requestCode,
							responseData.getExtra());
				} else {
					if (responseData.getMessage() != null) {
						iHttpRequest.accessFail(requestCode,
								responseData.getMessage());
					} else {
						iHttpRequest.accessFail(requestCode,
								Constants.RESPONSE_MAP_EMPTY);
					}
				}
			} else {
				if (!TextUtils.isEmpty(responseData.getMessage())) {
					iHttpRequest.accessFail(requestCode,
							responseData.getMessage());
				} else {
					iHttpRequest.accessFail(requestCode,
							Constants.RESPONSE_EMPTY);
				}
			}
		} else {
			iHttpRequest.accessFail(requestCode, Constants.RESPONSE_EMPTY);
		}
	}

	public void start(String url, RequestData requestData) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(RequestData.REQUESTDATA, requestData.toJsonString());
		StringRequest request = new StringRequest(Method.POST, url, map, this,
				this);
		if (null != requestData.toJsonString()) {
			// Logger.log("requestData:"
			// + requestData.toJsonString().replace("\\", ""));
		}
		BaseApplication.getRequestQueue().add(request);
	}

	public int getRequestCode() {
		return requestCode;
	}

	public void setRequestCode(int requestCode) {
		this.requestCode = requestCode;
	}

}
